
// 在index.js中
console.log('index.js')

const currRoute = window.location.href;
const erpRoute = [
  "https://erpnew.cwoa.net/#/WorkDaily",
  "https://erpnew.cwoa.net/#/home",
  "https://erpnew.cwoa.net/#/home",
  "https://erpnew.cwoa.net/#/AppointmentView"
]
const cwbkRoute = [
  "paas.cwbk.com/login"
]

erpRoute.includes(currRoute) ? autoHandleERP() : console.log("not in erp")
cwbkRoute.includes(currRoute) ? autoHandleCWBK() : console.log("not in cwbk")


function autoHandleERP() {
  injectERP() //页面注入
}

function loadCSS(url) {
  return new Promise((resolve, reject) => {
    const link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = url;
    link.onload = resolve;
    link.onerror = reject;
    document.head.appendChild(link);
  });
}

// 动态创建HTML
function createOverlay() {
  function createOverlay() {
    const htmlString = `
      <div id="overlay" style="
        position: fixed;
        top: 10px;
        left: calc(100% - 210px);
        right: 0;
        width: 350px;
        height: 200px;
        bottom: 0;
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 99999;
        background-color: rgba(0, 0, 0, 0.25);
        color: white;
        font-size: 18px;
        padding: 20px;
        box-sizing: border-box;">
        
        <button style="margin-right: 10px; background-color: #fff; color: #000; border: none; padding: 10px 20px; cursor: pointer;">创建今日erp日报</button>
        <button style="background-color: #fff; color: #000; border: none; padding: 10px 20px; cursor: pointer;">Button 2</button>
        
        <button id="closeButton" style="
          position: absolute;
          top: 10px;
          right: 10px;
          background-color: transparent;
          color: #fff;
          border: none;
          font-size: 24px;
          cursor: pointer;">X</button>
      </div>
    `;

    document.body.insertAdjacentHTML('beforeend', htmlString);

    // 为关闭按钮添加点击事件
    document.getElementById('closeButton').addEventListener('click', function () {
      this.parentElement.remove(); // 移除overlay元素
    });

    // 为创建今日erp日报按钮添加点击事件
    const createErpButton = document.querySelector('#overlay button:nth-child(1)');
    createErpButton.addEventListener('click', function () {
      // 假设的异步函数调用，实际应用中需替换为真实逻辑
      posterp().then(data => {
        console.log(data);
        disableButton(createErpButton, '已发送！', '填写erp日报', 3000);
        console.log('res:', data);
        document.querySelector('#overlay button:nth-child(2)').textContent = data.Value;
      }).catch(error => {
        console.error(error);
      });
    });

    // 为第二个按钮添加点击事件
    const button2 = document.querySelector('#overlay button:nth-child(2)');
    button2.addEventListener('click', function () {
      alert('Button 2 clicked!');
    });

    // 添加可拖动功能
    document.getElementById('overlay').addEventListener('mousedown', function (e) {
      let startX = e.clientX;
      let startY = e.clientY;
      let elemX = this.offsetLeft;
      let elemY = this.offsetTop;

      let overlay = document.getElementById('overlay')
      function onMouseMove(e) {
        let newX = elemX + e.clientX - startX;
        let newY = elemY + e.clientY - startY;
        overlay.style.left = newX + 'px';
        overlay.style.top = newY + 'px';
      }

      document.addEventListener('mousemove', onMouseMove);
      document.addEventListener('mouseup', function () {
        document.removeEventListener('mousemove', onMouseMove);
      }, { once: true });
    }, false);
  }

  // 调用函数创建覆盖层
  createOverlay();
}

// 使用上述函数
(async function () {
  try {
    // 假设你的CSS文件与content.js同目录或正确设置了相对路径
    await loadCSS(chrome.runtime.getURL('../static/css/floating_ball.css'));
    createOverlay();
  } catch (error) {
    console.error('加载CSS或创建元素时出错:', error);
  }
})();

function injectERP() {

  // test
  createOverlay()

  // const overlayDiv = document.createElement('div');
  // overlayDiv.id = 'overlay';
  // overlayDiv.style.position = 'fixed';
  // overlayDiv.style.top = '10px';
  // overlayDiv.style.left = 'calc(100% - 210px)';
  // overlayDiv.style.right = 0;
  // overlayDiv.style.width = '350px';
  // overlayDiv.style.height = '200px';
  // overlayDiv.style.bottom = 0;
  // overlayDiv.style.display = 'flex';
  // overlayDiv.style.justifyContent = 'center';
  // overlayDiv.style.alignItems = 'center';
  // overlayDiv.style.zIndex = 99999;
  // overlayDiv.style.backgroundColor = 'rgba(0, 0, 0, 0.25)';
  // overlayDiv.style.color = 'white';
  // overlayDiv.style.fontSize = '18px';
  // overlayDiv.style.padding = '20px';
  // overlayDiv.style.boxSizing = 'border-box';

  // document.body.appendChild(overlayDiv);

  // // 可以拖动
  // document.getElementById('overlay').addEventListener('mousedown', function (e) {
  //   let overlay = document.getElementById('overlay')
  //   let startX = e.clientX;
  //   let startY = e.clientY;
  //   let elemX = this.offsetLeft;
  //   let elemY = this.offsetTop;

  //   function onMouseMove(e) {
  //     let newX = elemX + e.clientX - startX;
  //     let newY = elemY + e.clientY - startY;

  //     // 设置新的位置
  //     overlay.style.left = newX + 'px';
  //     overlay.style.top = newY + 'px';
  //   }
  //   // 鼠标按下时，开始监听mousemove事件
  //   document.addEventListener('mousemove', onMouseMove);
  //   // 当鼠标松开时，停止监听mousemove事件
  //   document.addEventListener('mouseup', function () {
  //     document.removeEventListener('mousemove', onMouseMove);
  //   }, { once: true });
  // }, false);


  // const button1 = document.createElement('button');
  // button1.textContent = '创建今日erp日报';
  // button1.style.marginRight = '10px';
  // button1.style.backgroundColor = '#fff';
  // button1.style.color = '#000';
  // button1.style.border = 'none';
  // button1.style.padding = '10px 20px';
  // button1.style.cursor = 'pointer';

  // const button2 = document.createElement('button');
  // button2.textContent = 'Button 2';
  // button2.style.backgroundColor = '#fff';
  // button2.style.color = '#000';
  // button2.style.border = 'none';
  // button2.style.padding = '10px 20px';
  // button2.style.cursor = 'pointer';

  // overlayDiv.appendChild(button1);
  // overlayDiv.appendChild(button2);

  // // 第一个按钮添加事件监听
  // let res
  // button1.addEventListener('click', function () {
  //   posterp()
  //     .then(data => {
  //       console.log(data);
  //       res = data
  //       disableButton(button1, '已发送！', '填写erp日报', 3000)
  //       console.log('res:', res)
  //       button2.textContent = res.Value
  //     })
  //     .catch(error => {
  //       console.error(error);
  //     })
  // });

  // // 第二个按钮添加事件监听
  // button2.addEventListener('click', function () {
  //   alert('Button 2 clicked!');
  // });

  // const closeButton = document.createElement('button');
  // closeButton.textContent = 'X';
  // closeButton.style.position = 'absolute';
  // closeButton.style.top = '10px';
  // closeButton.style.right = '10px';
  // closeButton.style.backgroundColor = 'transparent'; // 使背景透明
  // closeButton.style.color = '#fff';
  // closeButton.style.border = 'none';
  // closeButton.style.fontSize = '24px';
  // closeButton.style.cursor = 'pointer';

  // closeButton.addEventListener('click', function () {
  //   overlayDiv.remove(); // 移除overlay元素
  // });

  // overlayDiv.appendChild(closeButton);

}

function autoHandleCWBK() {
  try {
    // 获取input元素
    var input = document.querySelector('#user');
    var input2 = document.querySelector('#password');
    // 填入指定的字符串
    input.value = "product";
    input2.value = "Bk@123456";
    // 延迟三秒后提交表单
    setTimeout(function () {
      var form = document.querySelector('#login-form');
      if (form) {
        form.submit();

        // 切换URL到指定路由
        console.log("重定向ing!")
        chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
          chrome.tabs.update(tabs[0].id, { url: "https://paas.cwbk.com/o/cmp_saas/#/home" });
        });
        console.log("重定向ing!")
      }
    }, 1000);
  } catch (error) {
    console.error("出错了：", error);
  }
}

